<template>
  <div>
    <el-card>
      <h2>购票</h2>
      <div style="margin-bottom: 16px;">
        <el-input v-model="keyword" placeholder="搜索景点名称" style="width: 240px; margin-right: 8px;" @keyup.enter="load" clearable />
        <el-button type="primary" @click="load">搜索</el-button>
        当前余额：<b>{{ user.balance }}</b> 元
      </div>
      <el-table :data="spots" style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="stock" label="剩余数量" width="100" />
        <el-table-column label="数量" width="120">
          <template #default="scope">
            <div class="quantity-cell">
              <el-input-number 
                v-model="quantities[scope.row.id]" 
                :min="1" 
                :max="scope.row.stock || 1" 
                controls-position="right"
                style="width: 90px;"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" @click="buy(scope.row)">购买</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const spots = ref([])
const quantities = ref({})
const user = ref(JSON.parse(sessionStorage.getItem('user') || '{}'))
const keyword = ref('')
const load = async () => {
  const res = await axios.get('/api/scenic-spots/page', { params: { page: 1, size: 100, keyword: keyword.value } })
  spots.value = res.data.data.records
}
onMounted(load)
async function buy(s) {
  const quantity = Number(quantities.value[s.id]) || 1
  if (!Number.isInteger(quantity) || quantity < 1) {
    ElMessage.error('数量必须为正整数')
    return
  }
  if (quantity > s.stock) {
    ElMessage.error('购买数量不能超过剩余库存')
    return
  }
  const total = s.price * quantity
  if (user.value.balance < total) {
    ElMessage.error('余额不足')
    return
  }
  try {
    const res = await axios.post('/api/orders', {
      userId: user.value.id,
      scenicSpotId: s.id,
      quantity
    })
    // 购票成功后刷新用户余额
    const userRes = await axios.get('/api/users/me', { params: { username: user.value.username } })
    user.value = userRes.data.data
    sessionStorage.setItem('user', JSON.stringify(user.value))
    ElMessage.success('购票成功，余额已更新！')
    load()
  } catch (e) {
    ElMessage.error(e.response?.data?.msg || '购票失败')
  }
}
</script>
<style>
.quantity-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.el-input-number .el-input__inner {
  text-align: center;
  width: 100% !important;
  min-width: 0;
  font-size: 16px;
  color: #222;
  background: #fff;
}
</style> 